package org.cable.link.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.cable.common.enums.BizCodeEnum;
import org.cable.common.enums.EventMessageType;
import org.cable.common.exception.BizException;
import org.cable.common.model.EventMessage;
import org.cable.link.service.ShortLinkService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 消费者监听-c端新增短链
 * @author hsj
 * @date 2023/10/31 14:58
 */
@Component
@Slf4j
@RabbitListener(queuesToDeclare = {
        @Queue("short_link.add.link.queue") })
public class ShortLinkAddLinkMqListener {

    @Autowired
    private ShortLinkService shortLinkService;

      @RabbitHandler
      public void shortLinkHandler(EventMessage eventMessage, Message message, Channel channel) throws IOException {
          log.info("ShortLinkAddLinkMqListener监听到消息内容:{}",message);
          long tag = message.getMessageProperties().getDeliveryTag();

          try {
            eventMessage.setEventMessageType(EventMessageType.SHORT_LINK_ADD_LINK.name());
            shortLinkService.handleAddShortLink((eventMessage));
          }catch (Exception e){
              log.error("消费失败:{}",e);
              throw new BizException(BizCodeEnum.MQ_CONSUMER_EXCEPTION);
          }

          log.info("消费成功:{}",eventMessage);
          //确认消费成功
          channel.basicAck(tag,false);

      }

}
